package impl.gui.listeners;

import impl.core.UDecideManager;
import impl.gui.util.UtilityAssertionRenderer;
import impl.util.BrowserLauncher;

import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JTable;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import org.semanticweb.owlapi.model.OWLNamedIndividual;

public class ChoiceListListener extends MouseAdapter implements ListSelectionListener {

	private static final String	WIKI_LINK_PROPERTY	= "http://dbpedia.org/ontology/wikiLink";

	private JTable				choiceUtilityTable;

	public ChoiceListListener(JTable choiceUtilityTable) {
		this.choiceUtilityTable = choiceUtilityTable;
	}

	@Override
	public void valueChanged(ListSelectionEvent e) {
		if (e.getValueIsAdjusting()) {
			return;
		} else if (this.choiceUtilityTable.getSelectedRow() == -1) {
			UDecideManager.getInstance().getGUI().setUtilityAssertionRenderer(new UtilityAssertionRenderer());
		} else {
			UDecideManager.getInstance().getGUI().clearUtilityAssertionSelections();

			OWLNamedIndividual selectedIndividual = (OWLNamedIndividual) this.choiceUtilityTable.getModel().getValueAt(
					this.choiceUtilityTable.getRowSorter().convertRowIndexToModel(this.choiceUtilityTable.getSelectedRow()), 0);

			UDecideManager
					.getInstance()
					.getGUI()
					.setUtilityAssertionRenderer(
							new UtilityAssertionRenderer(UDecideManager.getInstance().getUDecideReasoner().getChoiceResult(selectedIndividual)
									.getInferredUtilityAssertions()));

			UDecideManager.getInstance().getOwlWorkspace().getOWLSelectionModel().setSelectedEntity(selectedIndividual);
		}
	}

	@Override
	public void mouseClicked(MouseEvent me) {
		if (me.getClickCount() == 2) {
			JTable table = (JTable) me.getSource();
			Point p = me.getPoint();
			int row = table.rowAtPoint(p);
			if (row != -1) {
				OWLNamedIndividual indi = (OWLNamedIndividual) table.getValueAt(row, 0);
				BrowserLauncher.browseWikipediaForDBPediaIndividual(indi);
			}
		}
	}

}
